package com.webframe.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.webframe.service.def.IUserService;
/**
 * @author lenovo
 *
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;

	@RequestMapping
	public String index(HttpServletRequest request,HttpServletResponse response)
	{
		return "/userManage/userManage";
	}
	/**
	 * 添加用户
	 */
	@RequestMapping("/addUser")
	public String addUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String login_name_ = request.getParameter("login_name_");
		String real_name_ = request.getParameter("real_name_");
		String email_ = request.getParameter("email_");
		String password_ = request.getParameter("password_");
		String org_id_ = request.getParameter("org_id_");
		String status_ = "1";
		if (org_id_==null || "".equals(org_id_.trim()) || password_==null || "".equals(password_.trim()) || email_==null || "".equals(email_.trim()) || login_name_==null || "".equals(login_name_.trim()) || real_name_==null || "".equals(real_name_.trim())) {
			outWrite(response,"系统检测到错误参数,添加用户失败,请刷新页面重试.");
			return null;
		}
		try {
			userService.addUser(login_name_, real_name_, email_, password_, org_id_, status_);
		} catch (org.springframework.dao.DuplicateKeyException e) {
			outWrite(response,"登录名已存在!");
		} catch (Exception e) {
			if (e instanceof org.springframework.dao.DataIntegrityViolationException) {
				outWrite(response,"登录名已存在!");
			}else{
				outWrite(response, e.getMessage());
			}
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 添加角色
	 */
	@RequestMapping("/addRole")
	public String addRole(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String role_ = request.getParameter("role_");
		String label_ = request.getParameter("label_");
		if (role_== null || "".equals(role_.trim()) || label_== null || "".equals(label_.trim())) {
			outWrite(response,"系统检测到错误参数,添加角色失败,请刷新页面重试.");
			return null;
		}
		try {
			userService.addRole(role_, label_);
		} catch (org.springframework.dao.DuplicateKeyException e) {
			outWrite(response,"角色代码已存在!");
		} catch (Exception e) {
			if (e instanceof org.springframework.dao.DataIntegrityViolationException) {
				outWrite(response,"登录名已存在!");
			}else{
				outWrite(response, e.getMessage());
			}
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 给用户设置是否有效
	 */
	@RequestMapping("/updateEnableForUser")
	public String updateEnableForUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id_ = request.getParameter("id_");
		String enabled_ = request.getParameter("enabled_");
		boolean enabled=false;
		if (id_==null || "".equals(id_.trim()) || enabled_==null || "".equals(enabled_.trim())) {
			outWrite(response,"系统检测到错误参数,设置有效性失败,请刷新页面重试.");
			return null;
		}
		try {
			enabled = Boolean.parseBoolean(enabled_);
			userService.updateEnableForUser(id_, enabled);
		} catch (Exception e) {
			outWrite(response, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 给用户添加角色
	 */
	@RequestMapping("/addRoleForUser")
	public String addRoleForUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String user_id_ = request.getParameter("USER_ID_");
		String role_id_ = request.getParameter("ROLE_ID_");
		if (user_id_==null || "".equals(user_id_.trim()) || role_id_==null || "".equals(role_id_.trim())) {
			outWrite(response,"系统检测到错误参数,分配角色失败,请刷新表格重试.");
			return null;
		}
		try {
			userService.addRoleForUser(user_id_, role_id_);
		} catch (Exception e) {
			outWrite(response, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 删除用户的角色
	 */
	@RequestMapping("/delRoleForUser")
	public String delRoleForUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String user_id_ = request.getParameter("USER_ID_");
		String role_id_ = request.getParameter("ROLE_ID_");
		if (user_id_==null || "".equals(user_id_.trim()) || role_id_==null || "".equals(role_id_.trim())) {
			outWrite(response,"系统检测到错误参数,注销角色失败,请刷新表格重试.");
			return null;
		}
		try {
			userService.delRoleForUser(user_id_, role_id_);
		} catch (Exception e) {
			outWrite(response, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改密码
	 */
	@RequestMapping("/updatePwdForUser")
	public String updatePwdForUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id_ = request.getParameter("id_");
		String password_old_ = request.getParameter("password_old_");
		String password_new_ = request.getParameter("password_new_");
		if (id_==null || "".equals(id_.trim()) || password_old_==null || "".equals(password_old_.trim()) || password_new_==null || "".equals(password_new_.trim())) {
			outWrite(response,"系统检测到错误参数,修改密码失败,请刷新页面重试.");
			return null;
		}
		try {
			userService.updatePwdForUser(id_, password_old_, password_new_);
		} catch (Exception e) {
			outWrite(response, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 重置密码
	 */
	@RequestMapping("/resetPwd")
	public String resetPwd(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String id_ = request.getParameter("id_");
		String password_new_ = request.getParameter("password_new_");
		try {
			userService.resetPwd(id_, password_new_);
		} catch (Exception e) {
			outWrite(response, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 根据用户名修改密码
	 */
	@RequestMapping("/updatePwdForUserName")
	public String updatePwdForUserName(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String name_ = request.getParameter("id_");
		String password_old_ = request.getParameter("password_old_");
		String password_new_ = request.getParameter("password_new_");
		if (name_==null || "".equals(name_.trim()) || password_old_==null || "".equals(password_old_.trim()) || password_new_==null || "".equals(password_new_.trim())) {
			outWrite(response,"系统检测到错误参数,修改密码失败,请刷新页面重试.");
			return null;
		}
		try {
			userService.updatePwdForUserName(name_, password_old_, password_new_);
		} catch (Exception e) {
			outWrite(response, e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 根据用户id查询组织结构名称
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/findOrgId")
	public String findOrgId(HttpServletRequest request,HttpServletResponse response) throws Exception 
	{ 
		List l=this.userService.findOrgId(request, response);
		if(l!=null&&l.size()>=1)
		{
		  outWrite(response, String.valueOf(((Map)l.get(0)).get("label_")));
		}
		return null;
	}	
	@RequestMapping("/modifyUser")
	public String modifyUser(HttpServletRequest request,HttpServletResponse response) throws Exception 
	{ 
		try {
			this.userService.modifyUser(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}	
	/**
	 * 
	 * 假删除 用户
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	 @RequestMapping("/doVirtualDelete")
	 public String doVirtualDelete(HttpServletRequest request,HttpServletResponse response) throws IOException{
	  	 String ID_ = request.getParameter("ID_");
	  	 String tableName = request.getParameter("tableName");
	  	 StringBuffer sb = new StringBuffer();
	  	 Boolean optFlag = false ;
	  	 try
			{
	  		 	this.userService.doVirtualDeleteById(tableName, ID_);
				optFlag = true ;
	  		 
			} catch (Exception e)
			{
				optFlag = false;
				e.printStackTrace();
			}finally{
				if(optFlag){
					sb.append("{success:true}");
				}else{
					sb.append("{success:false}");
				}
				outWrite(response,sb.toString());
			}
	  	return null;
	  }
	
	
	 /**
	    * 
	    * 作用:删除pid下所有的子节点(假删除)
	    * @param request
	    * @param response
	    * @return
	    * @throws IOException
	    */
	 	@RequestMapping("/doVirtualDeleteAllChildsByPid")
	   public String doVirtualDeleteAllChildsByPid(HttpServletRequest request,HttpServletResponse response) throws IOException{
	    	 String ID_ = request.getParameter("ID_");
	    	 String tableName = request.getParameter("tableName");
	    	 String pidColumnName = request.getParameter("pidColumnName");
	    	 String hasChild = request.getParameter("hasChild");
	    	 StringBuffer sb = new StringBuffer();
	    	 Boolean optFlag = false ;
	    	 try
	  		{
	    		  if ("true".equals(hasChild))
				{
	    			   userService.doVirtualDeleteAllChildsByPid(tableName, pidColumnName,ID_);
				}else{
					   userService.doVirtualDelete("update "+tableName+" set status_ = 0 where ID_ = '"+ID_+"'");
				}
	    		optFlag = true ;
	    		 
	  		} catch (Exception e)
	  		{
	  			optFlag = false;
	  			e.printStackTrace();
	  		}finally{
	  			if(optFlag){
	  				sb.append("{success:true}");
	  			}else{
	  				sb.append("{success:false}");
	  			}
	  			outWrite(response,sb.toString());
	  		}
	    	return null;
	    }
	   /**
	    * 根据用户获取对应角色的页头背景
	    * @param request
	    * @param response
	    * @return
	    * @throws Exception
	    */
	 	@RequestMapping("/getRoleBg")
		public String getRoleBg(HttpServletRequest request,HttpServletResponse response) throws Exception 
		{ 
			String uname = request.getParameter("uname");
			String path = request.getSession().getServletContext().getRealPath("")+"/download/bgimage/";
			String url = userService.getRolesUrl(uname,path);
			request.getSession().setAttribute("bgurl", url);
			outWrite(response, url);
			return null;
		}
}
